<template>
  <div>
    <BasicTable @register="registerTable">
      <!-- 表格工具栏按钮-->
      <template #toolbar>
        <a-button type="primary" @click="openUpdateModal"> 新增分类 </a-button>
      </template>
      <!-- 注释 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <!-- 新增 -->
    <AddCategory @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '@/components/Table';

  import { useModal } from '@/components/Modal';
  import AddCategory from './add.vue';
  import { h } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Switch } from 'ant-design-vue';
  import { update, deleteById, pager } from '@/api/exam/questionCategory';
  import { formatToDateTime } from '@/utils/dateUtil';

  // 自定义组件名称, 默认为文件名
  defineOptions({ name: 'Category' });

  type CheckedType = boolean | string | number;

  // 搜索面板
  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '分类名称',
      component: 'Input',
      colProps: { span: 8 },
    },
    {
      field: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
      colProps: { span: 8 },
    },
  ];

  // 表格列
  const columns: BasicColumn[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '分类名称',
      dataIndex: 'category',
      width: 120,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      width: 150,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      format: (text) => {
        return formatToDateTime(text);
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.status === 1,
          checkedChildren: '停用',
          unCheckedChildren: '启用',
          loading: record.pendingStatus,
          onChange(checked: CheckedType) {
            record.pendingStatus = true;
            const newStatus = checked ? 1 : 0;
            const { createMessage } = useMessage();
            updateStatus(record.id, newStatus)
              .then(() => {
                record.status = newStatus;
                createMessage.success(`已成功修改分类状态`);
              })
              .catch(() => {
                createMessage.error('修改分类状态失败');
              })
              .finally(() => {
                record.pendingStatus = false;
              });
          },
        });
      },
    },
  ];

  const [registerModal, { openModal }] = useModal();

  // 表格
  const [registerTable, { reload }] = useTable({
    title: '分类列表',
    api: pager,
    columns,
    // 搜索框配置: 是否打开搜索框、搜索框配置
    useSearchForm: true,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    // 表格配置:
    showTableSetting: true, // 是否显示设置按钮
    bordered: true, // 是否包含边框
    showIndexColumn: false, // 是否包含索引列
    // 表格操作按钮
    actionColumn: {
      width: 80, // 按钮列宽度
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: undefined,
    },
  });

  function openUpdateModal() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete(record: Recordable) {
    await deleteById(record.id);
    reload();
  }

  function handleSuccess() {
    reload();
  }

  async function updateStatus(id: number, status: number) {
    return update(id, { status });
  }
</script>
